<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab">
                    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="104px">
                        <el-form-item label="商品编码/69码" prop="content">
                            <el-input v-model="queryParams.content" placeholder="请输入" clearable style="width: 220px"
                                @keyup.enter="handleQuery" />
                        </el-form-item>
                        <el-form-item label="类目" prop="categoryIds">
                            <el-cascader v-model="queryParams.categoryIds" :options="options" style="width: 220px"
                                filterable clearable ref="categoryRef" @change="handleChange" placeholder="请选择"
                                :props="{ checkStrictly: true }" />
                        </el-form-item>
                        <el-form-item label="商品名称" prop="styleName">
                            <el-input v-model="queryParams.styleName" placeholder="请输入商品名称" clearable
                                style="width: 220px" @keyup.enter="handleQuery" />
                        </el-form-item>

                        <el-form-item label="供应商" prop="supplierId">
                            <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" clearable filterable
                                v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" remote
                                :remote-method="searchQuery" class="supplierSelect" style="width: 220px"
                                :loading="supplierQueryLoading" @clear="handleClear">
                                <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value">
                                </el-option>
                                <template v-if="supplierLoading">
                                    <div class="supplierSelect_icon">
                                        <el-icon class="el-select-loading__icon">
                                            <Loading />
                                        </el-icon>
                                        <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                                    </div>
                                </template>
                                <template #loading>
                                    <svg class="circular" viewBox="0 0 50 50">
                                        <circle class="path" cx="25" cy="25" r="20" fill="none" />
                                    </svg>
                                </template>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="多次变价" prop="isFirstAudit">
                            <el-select style="width: 220px" v-model="queryParams.isFirstAudit" placeholder="请选择是否多次变价"
                                filterable clearable>
                                <el-option v-for="dict in hm_cooperation_mode" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="部门类型" prop="types">
                            <el-select v-model="queryParams.types" placeholder="请选择部门类型" clearable filterable
                                @change="(e: string) => { departmentTypeChange('type', e) }" style="width: 220px">
                                <el-option v-for="dict in departmentTypeList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="部门名称" prop="recruiterDeptId">
                            <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择部门名称" clearable filterable
                                @change="deptChange" style="width: 220px">
                                <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="人员名称" prop="recruiterUserId">
                            <el-select v-model="queryParams.recruiterUserId" placeholder="请选择人员名称" clearable filterable
                                style="width: 220px">
                                <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="审批结果" prop="statuss">
                            <el-select v-model="queryParams.statuss" placeholder="请选择审批结果" clearable filterable
                                style="width: 220px" @change="statusChange">
                                <el-option v-for="dict in statusList" :key="dict.userId" :label="dict.userName"
                                    :value="dict.userId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="初次发起时间" prop="putTime">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="putTime" type="daterange"
                                @change="pickerChange" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                                style="width: 220px" />
                        </el-form-item>
                    </el-form>
                    <div class="form_button">
                        <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                        <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
                    </div>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'核价部变价审批变价历史'"
                    @updateColumn="getColmun"></right-toolbar>
            </template>
            <el-table v-loading="loading" :data="supplierAddProductsList" border row-key="productsId"
                @header-dragend="dragEnd">
                <el-table-column v-for="(item, index) in pricingHistoryColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <div v-if="item.prop == 'changeHmMechanismsLists'">
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsLists &&
                                scope.row.changeHmMechanismsLists[0] ||
                                null,
                                '一') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsLists &&
                                scope.row.changeHmMechanismsLists[1] ||
                                null,
                                '二') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsLists &&
                                scope.row.changeHmMechanismsLists[2] ||
                                null,
                                '三') }}</div>
                        </div>
                        <div v-if="item.prop == 'changeHmMechanismsListsOne'">
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsListsOne &&
                                scope.row.changeHmMechanismsListsOne[0] ||
                                null,
                                '一') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsListsOne &&
                                scope.row.changeHmMechanismsListsOne[1] ||
                                null,
                                '二') }}</div>
                            <div>{{ computedMechanism(scope.row.changeHmMechanismsListsOne &&
                                scope.row.changeHmMechanismsListsOne[2] ||
                                null,
                                '三') }}</div>
                        </div>
                        <span v-if="item.prop == 'stockAuditStatus'">
                            <div class="color_theme">{{
                                scope.row.stockAuditStatus === 0 && scope.row.changeAuditStatus == 2 ? '待接收'
                                    : scope.row.stockAuditStatus === 0 && scope.row.changeAuditStatus == 1 ? '-'
                                        : scope.row.stockAuditStatus === 2 && scope.row.changeAuditStatus == 1 ? '-'
                                            : scope.row.stockAuditStatus === 2 && scope.row.changeAuditStatus == 2 ? '已接收' : '' }}
                            </div>
                        </span>
                        <span v-if="item.prop == 'changeAuditStatus'">
                            <div class="color_theme">{{ scope.row.changeAuditStatus === 1 ? '已驳回' : '已通过' }}</div>
                        </span>
                        <span v-if="item.prop == 'pricingAuditTime'">
                            <div class="color_theme">{{
                                scope.row.changeAuditStatus === 0 || scope.row.changeAuditStatus === 1 ? '' :
                                    scope.row.pricingAuditTime }}</div>
                        </span>
                        <span v-if="item.prop == 'type'">{{ scope.row.type == 1 ? '研发部' : '招商部' }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleInfo(scope.row)" v-throttle:click
                            class="color_theme">查看详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page-sizes="[10, 20, 30, 50, 100, 200]"
                v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="paginationChange" />
        </el-card>
        <!--商品详情抽屉 -->
        <commodityHistorydetails @doClose="commoditydetailsClose" :commoditydetailsData="commoditydetailsData"
            :type="'productSelectionPricing'" :dialogInfoVisible="dialogInfoVisible"></commodityHistorydetails>
    </div>
</template>
<script setup name="pricingHistory" lang="ts">
const { proxy } = getCurrentInstance() as any;
import commodityHistorydetails from './commodityHistorydetails.vue'
import { getPricingHistoryList, getPricingById } from '@/api/group/productSelectionPricing'
import { QualityControlQuery, ContractTable } from '@/api/group/productSelectionPricing/types';
import { getUserList, getSystemList } from '@/api/group/qualityControl'
import { loginSupplierList } from '@/api/group/supplier/index'
import { getCategoryLists } from '@/api/group/productOutbound'
import { listColumn } from '@/api/system/column/index'
const pricingHistoryColumns = ref()
const hm_cooperation_mode = ([
    { label: '是', value: '0' },
    { label: '否', value: '1' }
])
const columnData = ref()

const commoditydetailsData = ref<any>()
const dialogInfoVisible = ref(false)

const activeTab = ref('qualityControl');
const showSearch = ref(true);
const loading = ref(true);
const total = ref(0);
const supplierAddProductsList = ref<ContractTable[]>([]);
const queryFormRef = ref<ElFormInstance>();

// 部门类型
const departmentTypeList = ref<{ deptId: string; deptName: string; }[]>([])
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const categoryRef = ref();
const options = ref()
const statusList = ref<{ userName: string; userId: string }[]>([
    { userName: '已驳回', userId: '1' },
    { userName: '已通过', userId: '2' },
]);
const supplierNameOptions = ref<any[]>([])
const supplierNameDate = ref({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierQueryLoading = ref(false)
const supplierLoading = ref(true)
const supplierNametotal = ref()
const queryLoading = ref(false)
// 时间
const putTime = ref()

const data = reactive<PageData<{}, QualityControlQuery>>({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditDept: 2,
        status: '1,2',
        statuss: undefined,
        categoryId: undefined,
        categoryIds: undefined,
        styleName: undefined,
        cooperationMode: undefined,
        recruiterDeptId: undefined,
        recruiterUserId: undefined,
        supplierId: undefined,
        content: undefined,
        isFirstAudit: undefined,
        requestStartTime: undefined,
        requestEndTime: undefined,
        types: undefined
    },
    rules: {}
});
const { queryParams } = toRefs(data);
// 直播机制
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }
}

// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.id
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {
    if (val) {
        categoryRef.value.togglePopperVisible()
        queryParams.value.categoryIds = val[val.length - 1]
        queryParams.value.categoryId = val.join(',')
    }
}
// 获取类目
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
/**
 * 部门筛选
 */
const departmentTypeChange = async (type: string, id: string) => {
    deptList.value = []
    recruiterList.value = []
    queryParams.value.recruiterDeptId = undefined
    queryParams.value.recruiterUserId = undefined
    if (id) {
        const res = await getSystemList({ parentId: id })
        if (type === 'init') {
            departmentTypeList.value = res.data
        } else {
            deptList.value = res.data
        }
    }
}
// 类目
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
// select懒加载
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}
// 根据招商部获取招商员
const deptChange = async (event: string) => {
    queryParams.value.recruiterUserId = undefined
    if (event) {
        const res = await getUserList({ deptId: event })
        recruiterList.value = res.rows
    } else {
        recruiterList.value = []
    }
}
// 查询列表
const getList = async () => {
    try {
        loading.value = true;
        let params = {
            ...queryParams.value,
            recruiterDeptId: queryParams.value.recruiterDeptId ? queryParams.value.recruiterDeptId : queryParams.value.types
        }
        const res = await getPricingHistoryList(params);
        supplierAddProductsList.value = res.rows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
// 核价状态筛选
const statusChange = () => {
    if (queryParams.value.statuss != '') {
        queryParams.value.status = queryParams.value.statuss
    } else {
        queryParams.value.status = '1,2'
    }
}
// 搜索按钮操作
const handleQuery = () => {
    if (!queryParams.value.categoryIds) {
        queryParams.value.categoryId = undefined
    }
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
// 重置按钮操作
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    queryParams.value.status = '1,2'
    queryParams.value.categoryId = undefined
    putTime.value = undefined
    queryParams.value.requestStartTime = undefined
    queryParams.value.requestEndTime = undefined
    recruiterList.value = []
    deptList.value = []
    handleClear();
    handleQuery();
};
// 完成时间筛选
const pickerChange = (val: string[]) => {
    if (val && val.length) {
        queryParams.value.requestStartTime = val[0]
        queryParams.value.requestEndTime = val[1]
    } else {
        queryParams.value.requestStartTime = undefined
        queryParams.value.requestEndTime = undefined
    }
}
// 导出按钮操作
const handleExport = () => {
    proxy?.downloadAsync("basic/changeAudit/getPricingChangeHistoryExport", {
        ...queryParams.value,
        recruiterDeptId: queryParams.value.recruiterDeptId ? queryParams.value.recruiterDeptId : queryParams.value.types
    }, `变价历史_${new Date().getTime()}.xlsx`)
}
// 查看商品详情
const handleInfo = (row: ContractTable) => {
    nextTick(async () => {
        const res: any = await getPricingById({ id: row.id });
        res.data.bigVideos = import.meta.env.VITE_APP_PIC_URL + res.data.bigVideo
        commoditydetailsData.value = res.data
        commoditydetailsData.value.hmChangeAuditLogVos = res.data.hmChangeAuditLogVos.filter((item: any) => {
            return item.stockAuditStatus !== 2
        })
        dialogInfoVisible.value = true;
    });
};
// 商品详情关闭
const commoditydetailsClose = () => {
    dialogInfoVisible.value = false;
}
// 获取colmun
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('核价部变价审批变价历史')
    pricingHistoryColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
onMounted(async () => {
    queryParams.value.pageNum = 1;
    departmentTypeChange('init', '1861962988832542721')
    await getColmun();
    await getList();
    getHmSupplierList();
    getCategoryList();
});
</script>
<style lang="scss" scoped>
.two-line {
    overflow: hidden;
    display: -webkit-box;
    /* 将对象作为弹性伸缩盒子模型显示 */
    -webkit-line-clamp: 2;
    /* 行数，值可以改，表示展示X行后多余的缩略展示 */
    -webkit-box-orient: vertical;
    /* 设置或检索伸缩盒对象的子元素的排列方式 */
    word-break: break-all;
}

.mb96 {
    margin-bottom: 96px;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}

.circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
}

.path {
    animation: loading-dash 1.5s ease-in-out infinite;
    stroke-dasharray: 90, 150;
    stroke-dashoffset: 0;
    stroke-width: 2;
    stroke: var(--el-color-primary);
    stroke-linecap: round;
}

.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: initial;
    pointer-events: none;
    color: var(--el-color-info);
    font-size: 12px;

    &__icon {
        font-size: 16px;
        animation: rotate 1.5s linear infinite;
    }

    &__tips {
        margin-left: 6px;
    }

    @keyframes rotate {
        from {
            transform: rotate(0deg);
        }

        to {
            transform: rotate(360deg);
        }
    }
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}
</style>